package main

import (
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"github.com/fatih/color"
)

const uploadDir = "/cloudtfs"
const MAX_FILE_SIZE = 512 // 512 Мб

func uploadHandler(w http.ResponseWriter, r *http.Request) {

	err := r.ParseMultipartForm(MAX_FILE_SIZE << 20)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	files := r.MultipartForm.File["files"]

	for _, fileHeader := range files {
		log.Printf("%s   Requested file upload for: %s", color.New(color.FgWhite, color.BgMagenta).SprintFunc()("UPLOAD"), fileHeader.Filename)

		file, err := fileHeader.Open()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer file.Close()

		filePath := filepath.Join(uploadDir, fileHeader.Filename)

		fileOnDisk, err := os.Create(filePath)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		_, err = io.Copy(fileOnDisk, file)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		fileOnDisk.Close()

	}

	w.Write([]byte("File uploaded successfully"))
}

func downloadHandler(w http.ResponseWriter, r *http.Request) {

	fileName := r.URL.Query().Get("name")

	log.Printf("%s Requested file download for: %s", color.New(color.FgWhite, color.BgYellow).SprintFunc()("DOWNLOAD"), fileName)

	if fileName == "" {
		http.Error(w, "File name is required", http.StatusBadRequest)
		return
	}

	filePath := filepath.Join(uploadDir, fileName)
	file, err := os.Open(filePath)
	if err != nil {
		http.Error(w, "File not found", http.StatusNotFound)
		return
	}
	defer file.Close()

	fi, _ := file.Stat()
	fileSize := strconv.FormatInt(fi.Size(), 10)

	w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Length", fileSize)

	fileData, err := ioutil.ReadAll(file)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(fileData)
}
